import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';

const VUE_APP_STORAGE_PREFIX = import.meta.env.VITE_STORAGE_PREFIX;
export const setToken = (token: string) => {
  uni.setStorageSync(`${VUE_APP_STORAGE_PREFIX}_TOKEN`, token);
};

export const getToken = () => {
  return uni.getStorageSync(`${VUE_APP_STORAGE_PREFIX}_TOKEN`);
};

export const setCurLanguage = (curLanguage: string) => {
  return uni.setStorageSync(`${VUE_APP_STORAGE_PREFIX}_LANGUAGE`, curLanguage);
};

export const getCurLanguage = () => {
  return uni.getStorageSync(`${VUE_APP_STORAGE_PREFIX}_LANGUAGE`);
};

export const setUserInfo = (data: any) => {
  uni.setStorageSync(`${VUE_APP_STORAGE_PREFIX}_USER_INFO`, JSON.stringify(data));
};

export const getUserInfo = () => {
  const data = uni.getStorageSync(`${VUE_APP_STORAGE_PREFIX}_USER_INFO`);

  try {
    if (data) return JSON.parse(data);
  } catch (e) {
    return null;
  }
};

/**
 * 格式化富文本内容，确保图片宽度自适应并移除不必要的标签属性。
 * @param {string} originalHtml - 原始的 HTML 字符串。
 * @returns {string} - 自适应图片宽度的格式化后的 HTML 字符串。
 */
export const formatRichText = (originalHtml: string): string => {
  if (!originalHtml) return '';

  // 解码 HTML 实体并移除 <br/> 标签
  let formattedHtml = originalHtml
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/<br\s*\/?>/gi, '');

  // 调整 <img> 标签以实现响应式，并移除宽度和高度的内联样式
  formattedHtml = formattedHtml.replace(/<img([^>]*?)(style="[^"]*")?([^>]*?)>/gi, (match, pre, style, post) => {
    return `<img${pre}${post} style="width:100%;height:auto;display:block;margin:0;">`;
  });

  // 确保所有内联样式使用 max-width 实现响应式
  formattedHtml = formattedHtml.replace(/style="([^"]*)"/gi, (fullMatch, styles) => {
    const responsiveStyles = styles.replace(/width\s*:\s*[^;]+;?/gi, 'max-width:100%;').replace(/height\s*:\s*[^;]+;?/gi, 'height:auto;');
    return `style="${responsiveStyles}"`;
  });

  return formattedHtml;
};

export const showToast = (title = '加载中', duration = 2000, onClose?: Function) => {
  uni.showToast({
    title,
    duration,
    icon: 'none',
    mask: true,
  });
  if (onClose) {
    setTimeout(() => {
      onClose();
    }, duration);
  }
};

export const dateFormat = (time: string, format?: string, isTime = false) => {
  if (isTime) {
    dayjs.extend(duration);
    const timeData = dayjs.duration(time);
    return timeData.format(format);
  }
  return dayjs(time).format(format || 'YYYY-MM-DD HH:mm');
};

export const checkMobile = (value: string) => {
  return /^1[3456789]\d{9}$/.test(value);
};

export const checkEmail = (value: string) => {
  return /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)])/.test(
    value,
  );
};
export const checkPassword = (value: string) => {
  return /^.{6,20}$/.test(value);
};

export const deepCopy = (obj: any) => JSON.parse(JSON.stringify(obj));

/**
 * @description: 通过年和月返回这个月的天数
 * @param year 年
 * @param month 月
 * @return day 天数
 */
export const monthToDay = (year: number, month: number) => {
  let day = 0;
  switch (month) {
    case 2:
      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        day = 29;
      } else {
        day = 28;
      }
      break;
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      day = 31;
      break;
    case 4:
    case 6:
    case 9:
    case 11:
      day = 30;
      break;
  }
  return day;
};

/**
 * @description 个转万
 * @param value 传值
 * @param digits 保留位数
 * */
export const tenThousand = (value: number | string, digits = 2) => {
  value = Number(value);
  if (value >= 10000) {
    value = value / 10000;
    const temp = Math.pow(10, digits);
    return String(((value * temp) / temp).toFixed(digits));
  } else {
    return String(value);
  }
};
/**
 * @description 时间戳转化为时分秒格式
 * @param timer
 */
export const timeDiffFormat = (timer: number) => {
  if (!timer) return '';
  const toTen = (value: number) => {
    if (value < 10) {
      return `0${value}`;
    }
    return value;
  };
  let hours: string | number = parseInt(String((timer / 1000 / 60 / 60) % 24)); //时
  let minutes: string | number = parseInt(String((timer / 1000 / 60) % 60)); //分
  let seconds: string | number = parseInt(String((timer / 1000) % 60)); //秒
  hours = toTen(hours);
  minutes = toTen(minutes);
  seconds = toTen(seconds);
  if (hours > 0) {
    return `${hours}:${minutes}:${seconds}`;
  }
  return `${minutes}:${seconds}`;
};

export const API_URL = import.meta.env.VUE_APP_BASE_API;
export const PUBLIC_PATH_URL = import.meta.env.VUE_APP_PUBLIC_PATH_URL;
